import React, { createContext, useContext, useState, Dispatch, SetStateAction } from 'react';
import { AuthSessionData } from '../types';

// 定义 RoleContext 的值类型
export interface RoleContextType {
  sessionData?: AuthSessionData;
  setSessionData: (data:AuthSessionData)=>void;
  clearSessionData:()=>void,
  getSessionData:()=>AuthSessionData,
}
interface SearchContextType {
  keyword: string
  setKeyword:(keyword:string)=>void,
  getKeyword:()=>string,
}

  // 创建一个上下文，初始值为一个符合 RoleContextType 的对象
  const RoleContext = createContext<RoleContextType>({
    sessionData: null,
    clearSessionData:()=>{sessionStorage.removeItem("sessionData")},
    setSessionData: (data:AuthSessionData)=>{sessionStorage.setItem("sessionData",JSON.stringify(data))},
    getSessionData:():AuthSessionData=>{return null},

  });

  const SearchContext = createContext<SearchContextType>({
    keyword: '',
    setKeyword:(keyword:string)=>{},
    getKeyword:()=>{return ''},

  });

export const RoleProvider = ({ children }) => {
  const [sessionData,setSessionData2] = useState<AuthSessionData>(null)
  const clearSessionData = ()=>{
    sessionStorage.removeItem("sessionData");
    setSessionData(null);
  }
  const setSessionData = (data:AuthSessionData)=>{
    sessionStorage.setItem("sessionData",JSON.stringify(data))
    setSessionData2(data)
  }
  const getSessionData = ()=>{
    let text =  sessionStorage.getItem("sessionData")
    console.log("getSessionData",text)
    if(!text){
      return null
    }
    return JSON.parse(text)
  }
  return (
    <RoleContext.Provider value={{  sessionData, clearSessionData,setSessionData,getSessionData }}>
      {children}
    </RoleContext.Provider>
  );
};
export const SearchContextProvider = ({children})=>{
    const  [keyword,setKeyword] = useState<string>('')
    const getKeyword =()=>{
      return keyword;
    }
    return (
      <SearchContext.Provider value={{keyword,setKeyword,getKeyword}}>
        {children}
      </SearchContext.Provider>
    )
}
// 提供类型提示的 useRole 钩子
export const useRoleContext = (): RoleContextType => useContext(RoleContext);
export const useSearchContext = (): SearchContextType => useContext(SearchContext);